<template>
	<swiper class="home-swiper" :current="activeIndex" @change="change">
		<swiper-item v-for="(item,index) in tab" :key="index" class="swiper-item">
			<list-item :list="listCatchData[index]" :load="load[index]" @loadmore="loadmore"></list-item>
		</swiper-item>
	</swiper>
</template>

<script>
	import listItem from './list-item.vue'
	export default {
		name:"list",
		components: {
			listItem
		},
		props: {
			tab: {
				type: Array,
				default() {
					return []
				}
			},
			activeIndex: {
				type: Number,
				default: 0
			}
		},
		data() {
			return {
				list: [],
				// 缓存对象
				listCatchData: {},
				load: {},
				pageSize: 8
			};
		},
		created() {
		// 	// tab 还没有赋值
		// 	this.getList(0)
			uni.$on('update_article', (e) => {
				if(e === 'follow') {
					this.listCatchData = {}
					this.load = {}
					this.getList(this.activeIndex)
				}
			})
		},
		watch: {
			tab(newVal) {
				if(newVal.length === 0) return
				this.listCatchData = {}
				this.load = {}
				this.getList(this.activeIndex)
			}
		},
		methods: {
			change(e) {
				const {current} = e.detail
				// console.log(this.tab[current].name);
				
				this.$emit('change', current)
				// TODO 当数据不存在或者数据为 0 的情况下发送请求
				if(!this.listCatchData[current] || this.listCatchData[current].lenght === 0) {
					this.getList(current)
				}
			},
			getList(current) {
				if(! this.load[current]) {
					this.load[current] = {
						page: 1,
						loading: 'loading'
					}
				}
				this.$api.get_list({
					name: this.tab[current].name,
					page: this.load[current].page,
					pageSize: this.pageSize
				}).then(res => {
					// console.log(res);
					const {data} = res
					if(data.length === 0) {
						let oldLoad = {}
						oldLoad.loading = 'noMore'
						oldLoad.page = this.load[current].page
						this.$set(this.load,current,oldLoad)
						// 强制渲染页面
						this.$forceUpdate()
						return
					}
					let datalist = this.listCatchData[current] || []
					datalist.push(...data)
					// this.list = data
					// this.listCatchData[current] = data
					// 数据懒加载
					this.$set(this.listCatchData,current,datalist)
				})
			},
			loadmore() {
				if(this.load[this.activeIndex].loading === 'noMore') return
				this.load[this.activeIndex].page ++
				// console.log('触发上拉');
				this.getList(this.activeIndex)
			}
		}
	}
</script>

<style lang="scss">
	.home-swiper {
		height: 100%;
		.swiper-item {
			height: 100%;
			overflow: hidden;
		}
	}
</style>
